#!/bin/bash
usage='Usage: ./go0init.sh project_name' 
attention='project_name should not be "demoxyz", "jinquan", "jinquan7"'
if [ $# -ne 1 ]; then
        echo $usage
        echo $attention
else
project=$1


cat << EOF > $project/etc/myconf.yaml
Name: $project-api
Host: 0.0.0.0
Port: 8888
deploy:
  hosttype: "VMware VM"
  version: "go-zero $project v1.0"
EOF

echo "[add] $project/etc/myconf.yaml"



mkdir -p $project/internal/jinquan/

cat << EOF > $project/internal/jinquan/myconf.go
package jinquan

import (
  "log"
  "io/ioutil"
  "gopkg.in/yaml.v2"
  _ "flag"
   "path/filepath"
   "os"
)

type ST_MyConf struct {
  Deploy struct {
    HostType string \`yaml:"hosttype"\`
    Version string \`yaml:"version"\`
  } \`yaml:"deploy"\`
}

func load_myconf_file(f string) *ST_MyConf {
  dat,err := ioutil.ReadFile(f)
  if err != nil {
    log.Println(err.Error())
    return nil
  }
  var cfg ST_MyConf
  err = yaml.Unmarshal(dat, &cfg)
  if err != nil {
    log.Println(err.Error())
    return nil
  }
  return &cfg
}

var (
  MyConf *ST_MyConf
)

func LocateMyconf(myconf string) string {
  exe_dir,_ := filepath.Abs(filepath.Dir(os.Args[0]))
  config_file := exe_dir+"/"+myconf
  log.Printf("load configuration file: %s\n", config_file)
  return config_file
}

func InitMyconf(myconf string) {
  MyConf = load_myconf_file(LocateMyconf(myconf))
}
EOF
echo "[add] $project/internal/jinquan/myconf.go"

sed -i "s/\"$project\/internal\/svc\"/ \
\"$project\/internal\/svc\"\n \
\"$project\/internal\/jinquan\"/g" $project/$project.go

sed -i 's/flag.Parse()/ \
flag.Parse() \
jinquan.InitMyconf(*configFile)/g' $project/$project.go
sed -i 's/conf.MustLoad(\*configFile, \&c)/conf.MustLoad(jinquan.LocateMyconf(\*configFile), \&c)/g' $project/$project.go
sed -i "s/\"etc\/$project-api.yaml\"/\"etc\/myconf.yaml\"/g" $project/$project.go
echo "[modify] $project/$project.go"

fi
